/**
 * Created with JetBrains PhpStorm.
 * User: MeRo
 * Date: 17.09.13
 * Time: 18:11
 */

var templateOnClickRegisteredCounter = 0;

function generateSurface(data) {
    var $container = $('#new_surface, #load_surface');
    data['surface_x_size'] = parseInt(data['surface_x_size']);
    data['surface_y_size'] = parseInt(data['surface_y_size']);
    if (data['surface_public'] == '1') {
        data['surface_public'] = 'checked = "checked"';
    } else {
        data['surface_public'] = '';
    }

    $('#main .inside').html('<div id="surface" class="mod_article block"><div class="ce_text block"></div>');

    addStatusBar(data);
    addTemplateSelector();
    addGrid(data);

    $('#surfaceGrid .gridly .brick, #surfaceGrid .gridly .brickTemplate').on('dblclick', brickDoubleClicked);
    $('#surfaceGrid .gridly .brick, #surfaceGrid .gridly .brickTemplate').on('contextmenu', brickClicked);
}

function addStatusBar(data) {
    var surfaceStatus = '<div id="surfaceStatus">' +
        '<div class="surfaceStatusSection">' +
            '<label for="surface_name">Landschaftsname: </label><br /><br /><br />' +
            '<input type="text" name="surface_name" value="' + data['surface_name'] + '">' +
        '</div>' +
        '<div class="surfaceStatusSection">' +
            '<label for="surface_name">X-Gr&ouml;&szlig;e: </label><br /><br /><br />' +
            '<input type="number" name="surface_x_size" value="' + data['surface_x_size'] + '">' +
        '</div>' +
        '<div class="surfaceStatusSection">' +
            '<label for="surface_name">Y-Gr&ouml;&szlig;e: </label><br /><br /><br />' +
            '<input type="number" name="surface_y_size" value="' + data['surface_y_size'] + '">' +
        '</div>' +
        '<div class="surfaceStatusSection">' +
            '<label for="surface_name">Ver&ouml;ffentlichen: </label><br /><br /><br />' +
            '<input type="checkbox" name="surface_public" ' + data['surface_public'] + '>' +
        '</div>' +
        '<div class="surfaceStatusSection">' +
            '<label for="surface_description">Bemerkung:</label><br />' +
            '<textarea name="surface_description" cols="30" rows="2">' + data['surface_description'] + '</textarea>' +
        '</div>' +
    '</div>';

    $('#surface .ce_text').html(surfaceStatus);
}

function addTemplateSelector() {
    $('#surface .ce_text').append('<div id="templateSelectorContainer">' +
        '<div id="templateSelector" class="gradient">' +
            '<ul class="tabs">' +
                '<li class="tab1"><a href="#tab1">Gleise</a></li>' +
                '<li class="tab2"><a href="#tab2">Landschaft</a></li>' +
            '</ul>' +
            '<div class="tab" id="tab1"></div>' +
            '<div class="tab" id="tab2"></div>' +
        '</div>' +
    '</div>');

    initiateTabs($('#templateSelector .tabs'));


    $('#surfaceGrid .gridly .brick').on('click', brickClicked);
    getTemplateRails($('#templateSelector #tab1'));
    getTemplateLandscape($('#templateSelector #tab2'));
    addTemplateSliderEvents();
}

function getTemplateRails(targetElement) {
    var url = 'de/ajax/articles/template-rail';
    $.getJSON(url, function(data) {
        targetElement.html(data);
        addTemplateAddEvents();
    });
}

function getTemplateLandscape(targetElement) {
    var url = 'de/ajax/articles/template-landscape';
    $.getJSON(url, function(data) {
        targetElement.html(data);
        addTemplateAddEvents();
    });
};

function addTemplateSliderEvents() {
    $('#templateSelectorContainer .tabs li a').on('click', function() {
        if ($('#templateSelector').css('right') == '0px' && $(this).hasClass('active')) {
            $('#templateSelector').animate({
                right: "-202px"
            }, 1500);
        };
        if ($('#templateSelector').css('right') != '0px') {
            $('#templateSelector').animate({
                right: "0px"
            }, 1500);
        };
    });
}

function addTemplateAddEvents() {
    templateOnClickRegisteredCounter += 1;
    if (templateOnClickRegisteredCounter == 2) {
        $('#templateSelector .brickTemplate').on('click', function() {
            var element = $(this).outerHTML()/*.replace('railTemplate brickTemplate ', 'brick pointer')*/;
            $('#surfaceGrid .gridly').append(element);
            $('#surfaceGrid .gridly .brick, #surfaceGrid .gridly .brickTemplate').first().trigger('mousedown');
            $('#surfaceGrid .gridly .brick, #surfaceGrid .gridly .brickTemplate').last().trigger('mousedown');
            $('#surfaceGrid').trigger('click');

            $('#surfaceGrid .gridly .brick, #surfaceGrid .gridly .brickTemplate').last().on('dblclick', brickDoubleClicked);
            $('#surfaceGrid .gridly .brick, #surfaceGrid .gridly .brickTemplate').last().on('contextmenu', brickClicked);
        });
    }
}

function addGrid(data) {
    $('#surface .ce_text').append('<div id="surfaceGrid">');
    var bricks = data['surface_x_size'] * data['surface_y_size'];
    var brickArea = '<div class="gridly">';
    var brickAreaHeight = data['surface_y_size'] * 150 + (data['surface_y_size'] - 1) * 5;
    var brickAreaWidth  = data['surface_x_size'] * 150 + (data['surface_x_size'] - 1) * 5;

    for (var i = 0; i < bricks; i++) {
        brickArea = brickArea + '<div class="brick pointer"></div>';
    }

    brickArea = brickArea + '</div></div>';
    $('#surfaceGrid').append(brickArea);
    $('#surfaceGrid .gridly')
        .css('height', brickAreaHeight)
        .css('width',  brickAreaWidth)
    ;

    $('#surfaceGrid .gridly').gridly({
        base: 150, // px
        gutter: 5, // px
        columns: data['surface_x_size']
    });
}

function initiateTabs(tabs) {
    tabs.each(function(){
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = $(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active  = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
        $active.addClass('active');
        $content = $($active.attr('href'));

        // Hide the remaining content
        $links.not($active).each(function () {
            $($(this).attr('href')).hide();
        });

        // Bind the click event handler
        $(this).on('click', 'a', function(e) {
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active  = $(this);
            $content = $($(this).attr('href'));

            // Make the tab active.
            $active.addClass('active');
            $content.show();

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
}

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

function brickDoubleClicked() {
    if ($(this).hasClass('rotate1')) {
        $(this).removeClass('rotate1');
        $(this).addClass('rotate2');
    } else if ($(this).hasClass('rotate2')) {
        $(this).removeClass('rotate2');
        $(this).addClass('rotate3');
    } else if ($(this).hasClass('rotate3')) {
        $(this).removeClass('rotate3');
        $(this).addClass('rotate0');
    } else {
        $(this).removeClass('rotate0');
        $(this).removeClass('rotate2');
        $(this).removeClass('rotate3');
        $(this).addClass('rotate1');
    }
}

function brickClicked(e) {
    e.preventDefault();
    $(this).remove();
}
